package com.wzs.dao.impl;

import com.wzs.dao.IUserDao;
import com.wzs.model.User;
import com.wzs.model.UserCondition;
import com.wzs.util.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @author miaomiao
 * @version 1.0.0
 * @ClassName UserDao.java
 * @Description IUserDao接口的实现类
 * @createTime 2021-06-19- 11:26:00
 */
public class UserDao implements IUserDao {
    @Override
    public ArrayList<User> getUserByCondition(UserCondition condition) {

        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        ArrayList<User> users = new ArrayList<>();

        try {
            //1.获取连接
            conn = JdbcUtil.getConnection();
            //2、执行sql
            String sql = "select * from user where 1=1";
            if (condition.getName() != null && !condition.getName().equals("")) {
                sql += " and name like concat('%' ,?, '%')";
            }
            pstm = conn.prepareStatement(sql);

            if (condition.getName() != null && !"".equals(condition.getName())) {
                pstm.setString(1, condition.getName());
            }

            //3.获取结果
            rs = pstm.executeQuery();

            //5.读取数据
            while (rs.next()) {
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String password = rs.getString("password");
                User u = new User(id, name, password);
                users.add(u);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.close(conn, pstm, rs);
        }
        return users;
    }
}
